package covertjava.classloader;

import java.lang.reflect.Method;

/**
* <p>Loads a class using the DecoratingClassLoader and invokes class's main() method</p>
* <p>Copyright: Copyright (c) 2004 Sams Publishing</p>
* @author Alex Kalinovsky
* @version 1.0
*/
public class DecoratingLauncher {

    public static void main(String[] args) throws Exception {
        if (args.length < 1) {
            System.out.println("Missing command line parameter <main class>");
            System.out.println("Syntax: DecoratingLauncher [-Ddecorated.class.path=<path>] <main class> [<arg1>, [<arg2>]..]");
            System.exit(1);
        }

        DecoratingClassLoader decoratingClassLoader = new DecoratingClassLoader();
        decoratingClassLoader.setDecorator(new PrintingClassDecorator());
        Class mainClass = Class.forName(args[0], true, decoratingClassLoader);
//        Class mainClass = decoratingClassLoader.loadClass(args[0]);

        String[] mainArgs = new String[args.length - 1];
        System.arraycopy(args, 1, mainArgs, 0, args.length - 1);
        invokeMain(mainClass, mainArgs);
    }

    protected static void invokeMain(Class mainClass, String[] mainArgs) throws Exception {
        // Check if it can be run as an application first
        Class[] paramTypes = new Class[] {String[].class};
        Method main = mainClass.getMethod("main", paramTypes);
        main.invoke(null, new Object[]{mainArgs});
    }
}
